package com.pig4cloud.pig.sthcloud.util;

import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @author JRPF8P2
 */
@Component
public class CoordinateConverter {
    private static final int DECIMAL_PLACES = 8;
    private static final RoundingMode ROUNDING_MODE = RoundingMode.HALF_UP;
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00000000");

    public String validateInputDegrees (String dddmmMmmm,boolean isLatitude){

        if (dddmmMmmm == null || dddmmMmmm.isEmpty()) {
            return "数据为空";
        }

        // 解析坐标值
        double decimalDegrees = parseCoordinate(dddmmMmmm,isLatitude);

        if (Double.isNaN(decimalDegrees)){
            return "格式错误";
        }

        // 格式化输出（强制保留8位小数）
        return formatCoordinate(decimalDegrees);
    }
    public String validateInputDirection (String direction) {

        if(direction == null || direction.isEmpty()){
            return "数据为空";
        }
        if(!direction.matches("[NSEW]")){
            return "数据格式有误";
        }

        return direction;
    }
    private double parseCoordinate(String dddmmMmmm,boolean isLatitude) {

        int dotIndex = dddmmMmmm.indexOf('.');
        if (dotIndex < 1) {
            return Double.NaN;
        }
        if(isLatitude){
            if(dotIndex != 4){
                return Double.NaN;
            }
        }else if(dotIndex != 5){
            return Double.NaN;
        }

        // 提取度部分
        String degreesStr = dddmmMmmm.substring(0, dotIndex - 2);
        double degrees = Double.parseDouble(degreesStr);
        if(isLatitude){
            if(degrees >= 90){
                return Double.NaN;
            }
        }else if(degrees >= 180){
            return Double.NaN;
        }

        // 提取分部分（包括小数点）
        String minutesStr = dddmmMmmm.substring(dotIndex - 2);
        double minutes = Double.parseDouble(minutesStr);
        if(minutes >= 60){
            return Double.NaN;
        }

        return degrees + minutes / 60.0;
    }
        private String formatCoordinate(double value) {
            // 使用BigDecimal确保精确的四舍五入
            BigDecimal bd = BigDecimal.valueOf(value)
                    .setScale(DECIMAL_PLACES, ROUNDING_MODE);
            // 使用DecimalFormat强制保留8位小数
            return DECIMAL_FORMAT.format(bd.doubleValue());
    }
}